package com.foodorder.config;

import com.foodorder.entity.Admin;
import com.foodorder.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.time.LocalDateTime;
import java.util.Optional;

@Configuration
public class TestDataInitializer {

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    public CommandLineRunner initTestData() {
        return args -> {
            // 检查是否已存在管理员
            Optional<Admin> existingAdmin = adminRepository.findByUsername("admin");
            if (existingAdmin.isEmpty()) {
                System.out.println("初始化测试管理员账户...");
                
                // 创建测试管理员
                Admin admin = Admin.builder()
                        .username("admin")
                        .password(passwordEncoder.encode("123456"))
                        .name("系统管理员")
                        .phone("13800138000")
                        .email("admin@foodorder.com")
                        .avatar("/images/avatars/admin.jpg")
                        .role(Admin.AdminRole.SUPER_ADMIN)
                        .status(Admin.AdminStatus.ACTIVE)
                        .permissions("ALL")
                        .createdAt(LocalDateTime.now())
                        .updatedAt(LocalDateTime.now())
                        .build();
                
                adminRepository.save(admin);
                System.out.println("测试管理员账户创建成功: admin");
            } else {
                System.out.println("更新已存在的管理员账户密码...");
                Admin admin = existingAdmin.get();
                // 更新密码为123456
                admin.setPassword(passwordEncoder.encode("123456"));
                adminRepository.save(admin);
                System.out.println("管理员账户密码已更新: admin");
            }
        };
    }
} 